<template>
    <div style="padding: 0 10px">
        <div class="header">
            <StandardQueryCondition @comReturn="comReturn" @handleButton="handleButton"></StandardQueryCondition>
        </div>
        <div :class="{ isOpened: isOpen, noOpened: !isOpen }">
            <vxe-table
                :header-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :footer-cell-style="{ backgroundColor: '#e8f3ff', padding: '4px 0' }"
                :data="tableData"
                :key="tableKey + 'tableKey'"
                v-loading="loading"
                v-table-top="page.currentPage"
                border
                stripe
                resizable
                :auto-resize="true"
                show-footer
                :footer-method="getSummaries"
                :sort-config="{
                    defaultSort: { field: sortProp, order: sortOrder, orders: ['desc', 'asc', null] },
                }"
                @sort-change="changeTableSort"
                :resizable-config="{ minWidth: '60' }"
                :filter-config="{ iconNone: 'el-icon-search', iconMatch: 'el-icon-search', remote: true }"
                @filter-change="handleFilter"
                ref="table"
                show-header-overflow="tooltip"
                show-footer-overflow="tooltip"
                header-align="center"
                highlight-current-row
            >
                <vxe-column
                    v-for="item in showFieldList"
                    :field="item.id"
                    :title="item.content"
                    :key="item.content"
                    :filters="item.filters"
                    :filter-render="{ name: 'FilterComplex' }"
                    :align="getAlign(item)"
                    :min-width="item.minWidth || '105px'"
                    show-overflow="tooltip"
                    :sortable="item.sortable"
                >
                    <template #filter="{ $panel, column }" v-if="item.filterType === 'search'">
                        <div>
                            <el-select
                                v-model="option.value"
                                class="my-select"
                                v-for="(option, index) in column.filters"
                                :key="'my-select' + index"
                                placeholder=""
                                @change="$panel.changeOption($event, !!option.value, option)"
                            >
                                <el-option v-for="item in CompareDirection" :key="item" :value="item" :label="item"></el-option>
                            </el-select>
                            <el-input
                                ref="searchInput"
                                class="my-input"
                                type="type"
                                v-for="(option, index) in column.filters"
                                :key="index"
                                v-model="option.data"
                                @input="$panel.changeOption($event, !!option.data, option)"
                            />
                        </div>
                    </template>
                    <template slot-scope="scope">
                        <span v-if="item.render && typeof item.render === 'function'">
                            {{ item.render(scope.row[item.id], scope.row) || '--' }}
                        </span>
                        <span
                            v-else-if="
                                [
                                    'currentAmount',
                                    'frozenAmount',
                                    'unfrozenAmount',
                                    'usableAmount',
                                    'financingAmount',
                                    'szstdAmount',
                                    'szstdzhAmount',
                                    'ssstdzhAmount',
                                    'useRate',
                                ].includes(item.id)
                            "
                        >
                            {{ numberFormat(scope.row[item.id], 2) || '--' }}
                        </span>

                        <span v-else>
                            {{ scope.row[item.id] === 0 || (scope.row[item.id] && (scope.row[item.id] + '').trim()) ? scope.row[item.id] : '--' }}
                        </span>
                    </template>
                </vxe-column>
            </vxe-table>
            <RiskPagination :paging="page" @page-change="pageRet"></RiskPagination>
        </div>
        <RiskTableLayout
            title="页面布局"
            :visible.sync="layoutDialog"
            :field-list="tableColumns"
            :selected-field-list="selectedFieldList"
            :fixed-field-list="fixedFieldList"
            table-name="TN_STANDARD_MAX_WEALTH_TEST"
            @on-submit="onSubmit"
        />
    </div>
</template>
<script lang="ts">
import RiskPagination from '@/common/components/risk-pagination.vue';
import RiskTableLayout from '@/common/components/risk-table-layout.vue';
import { dateFormat, numberFormat } from '@/utils/tools';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import StandardQueryCondition from './standard-query-condition.vue';
import VXETable from 'vxe-table';
import { getTableLayout } from '@/common/api/commonApi';
import { standardStockExport, standardStockList } from '../api/comprehensive-info-query';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

// 创建一个简单的输入框筛选
VXETable.renderer.add('FilterComplex', {
    // 筛选模板
    // renderFilter(h, renderOpts, params): any {
    //     // return [`<FilterComplex params=${params}></FilterComplex>`];
    // },
    // 重置数据方法
    filterResetMethod(params) {
        const { options } = params;
        options.forEach((option) => {
            option.data = '';
            option.value = '';
        });
    },
    // 重置筛选复原方法（当未点击确认时，该选项将被恢复为默认值）
    filterRecoverMethod({ option }) {
        option.data = '';
        option.value = '';
    },
    // 筛选方法???
    filterMethod(params) {
        const { option, row, column } = params;
        const { data } = option;
        const cellValue = row[column.field];
        if (cellValue) {
            return cellValue.indexOf(data) > -1;
        }
        return false;
    },
});

@Component({ name: 'Standard', components: { RiskTableLayout, RiskPagination, StandardQueryCondition } })
export default class Standard extends Vue {
    dateFormat = dateFormat;

    isOpen: boolean = false;

    tableData: any[] = [];

    summary: any = {}; // 汇总行

    sortableObj = {
        fundId: 'L_FUND_ID',
        fundCode: 'VC_FUND_CODE',
        fundName: 'VC_FUND_NAME',

        assetId: 'L_ASSET_ID',

        assetName: 'VC_ASSET_NAME',

        basecombiId: 'L_BASECOMBI_ID',

        combiNo: 'VC_COMBI_NO',

        combiName: 'VC_COMBI_NAME',

        stockCode: 'VC_INTER_CODE',

        currentAmount: 'L_CURRENT_AMOUNT',

        frozenAmount: 'L_FROZEN_AMOUNT',

        unfrozenAmount: 'L_UNFROZEN_AMOUNT',

        usableAmount: 'usableAmount',
        stockNameSt: 'VC_STOCK_NAME',
        stockType: 'C_STOCK_TYPE_CODE',
        marketName: 'VC_MARKET_NAME',
        financingAmount: 'L_FINANCING_AMOUNT',
        szstdAmount: 'EN_SZSTD_AMOUNT',
        szstdzhAmount: 'EN_SZSTDZH_AMOUNT',
        ssstdzhAmount: 'EN_SSSTDZH_AMOUNT',
        useRate: 'N_USE_RATE',
    };

    tableColumns = [
        {
            content: '业务日期',
            id: 'businessDate',
            align: 'center',
            sortable: false,
            render: (value) => dateFormat(value),
        },
        {
            content: '产品序号',
            id: 'fundId',
            align: 'left',
            sortable: true,
        },
        {
            content: '产品编码',
            id: 'fundCode',
            sortable: true,
        },
        {
            content: '产品名称',
            id: 'fundName',
            align: 'left',
            sortable: true,
        },
        // {
        //     content: '资产单元编号',
        //     id: 'assetId',
        //     minWidth: '130px',
        //     align: 'left',
        //     sortable: true,
        // },
        // {
        //     content: '资产单元名称',
        //     id: 'assetName',
        //     minWidth: '130px',
        //     align: 'left',
        //     sortable: true,
        // },
        // {
        //     content: '组合序号',
        //     id: 'basecombiId',
        //     align: 'left',
        //     sortable: true,
        // },
        // {
        //     content: '组合编码',
        //     id: 'combiNo',
        //     align: 'left',
        //     sortable: true,
        // },
        // {
        //     content: '组合名称',
        //     id: 'combiName',
        //     align: 'left',
        //     sortable: true,
        // },
        {
            content: '证券代码',
            id: 'stockCode',
            align: 'left',
            sortable: true,
        },
        {
            id: 'stockNameSt',
            content: '证券名称',
            align: 'left',
            sortable: true,
        },
        { id: 'stockType', content: '证券类别', align: 'center', sortable: true },
        { id: 'marketName', content: '交易市场', align: 'center', sortable: true },
        {
            content: '库存数量',
            id: 'currentAmount',
            align: 'right',
            minWidth: '120px',
            filterType: 'search',
            filters: [{ data: '', value: '' }],
            currentAmountFilterDirection: '',
            sortable: true,
        },
        {
            content: '融券数量',
            id: 'frozenAmount',
            align: 'right',
            sortable: true,
        },
        {
            content: '融资数量',
            id: 'financingAmount',
            align: 'right',
            sortable: true,
        },
        {
            content: '解冻数量',
            id: 'unfrozenAmount',
            align: 'right',
            sortable: true,
        },
        {
            content: '可用数量',
            id: 'usableAmount',
            minWidth: '150px',
            align: 'right',
            filterType: 'search',
            filters: [{ data: '' }],
            usableAmountFilterDirection: '',
            sortable: true,
        },
        {
            content: '深交所当日转标准券数量',
            id: 'szstdAmount',
            align: 'right',
            minWidth: '200px',
            sortable: true,
        },
        {
            content: '深交所当日可转回标准券数量',
            id: 'szstdzhAmount',
            align: 'right',
            minWidth: '240px',
            sortable: true,
        },
        {
            content: '上交所当日可转回标准券数量',
            id: 'ssstdzhAmount',
            align: 'right',
            minWidth: '240px',
            sortable: true,
        },
        {
            content: '使用率(%)',
            id: 'useRate',
            align: 'right',
            minWidth: '120px',
            sortable: true,
        },
    ];

    CompareDirection = ['>', '<', '=', '>=', '<='];

    private page: pages = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    private sortProp: string = 'fundId'; // 排序字段

    private sortOrder: string = 'asc'; // 排序方式

    sort: string = 'L_FUND_ID ASC'; // 默认排序字段

    numberFormat = numberFormat;

    layoutDialog: boolean = false; // 布局显示值

    showFieldList: any[] = []; // 展示字段

    selectedFieldList: any[] = []; // 已选字段

    fixedFieldList: any[] = [
        {
            content: '业务日期',
            id: 'businessDate',
            align: 'center',
            sortable: false,
            render: (value) => dateFormat(value),
        },
        { id: 'fundId', content: '产品序号', align: 'left', sortable: true },
    ];

    searchParam: any = {}; // 查询条件

    loading: boolean = false; // 页面渲染

    tableKey: number = -1;

    isFirst: boolean = true;

    @Prop() activeValue: string;

    @Watch('activeValue', { immediate: true })
    async handleActiveValue() {
        if (this.activeValue === 'standard') {
            if (this.isFirst) {
                await this.queryLayout();
                this.getStandardTableData();
                this.isFirst = false;
            }
        }
    }

    getStandardTableData() {
        this.loading = true;
        return new Promise((resolve, reject) => {
            standardStockList({
                ...this.searchParam,
                sort: this.sort,
                paging: this.page,
            })
                .then((res: any) => {
                    if (res.total) {
                        // 使用率合计无意义
                        delete res.list[res.list.length - 1].useRate;
                        this.summary = res.list[res.list.length - 1];
                        this.tableData = res.list.slice(0, res.list.length - 1);
                    } else {
                        this.summary = {};
                        this.tableData = [];
                    }
                    this.page.total = res.total;
                    this.loading = false;
                    resolve(res);
                })
                .catch((err) => {
                    this.loading = false;
                    reject(err);
                });
        });
    }

    // 查询返回
    comReturn(obj) {
        this.isOpen = obj.isOpen;
        this.searchParam = obj.searchParam;
    }

    pageRet() {
        this.getStandardTableData();
    }

    // 分页
    pageChange(curPage: number): void {
        this.page.currentPage = curPage;
        this.getStandardTableData();
    }

    // 合计行
    getSummaries() {
        let arr = [];
        if (this.tableData.length) {
            let count = 0;
            let obj = this.tableData[0];
            let objR = this.summary;
            for (let item of this.showFieldList) {
                if (objR[item.id]) {
                    arr[count++] = numberFormat(objR[item.id], 2);
                } else {
                    arr[count++] = '--';
                }
            }
        }
        return [arr];
    }

    // 排序改变
    private changeTableSort(column): void {
        this.sortProp = column.property;
        this.sortOrder = column.order;
        let sortType = column.order == 'asc' ? 'ASC' : column.order == 'desc' ? 'DESC' : '';
        this.sort = this.sortableObj[column.property] + ' ' + sortType;
        this.pageChange(1);
    }

    // 筛选
    handleFilter($event): void {
        const { field, values, datas } = $event;
        let searchParams = this.searchParam;

        if (field == 'currentAmount' || field == 'usableAmount') {
            searchParams[field + 'FilterDirection'] = values.join('');
        }
        const col = this.tableColumns.find((i) => i.id === field);
        searchParams[field] = col.filterType === 'search' ? datas.join('') : values;
        this.pageChange(1);
    }

    /**
     * 提交成功后回调
     * @param {Object} 回调数据
     */
    async onSubmit(data) {
        await this.queryLayout();
    }

    // 获取页面布局信息
    async queryLayout() {
        let resList: any = await new Promise((resolve, reject) => {
            getTableLayout('TN_STANDARD_MAX_WEALTH_TEST')
                .then((res: any) => {
                    resolve(res);
                })
                .catch((err) => {
                    reject(err);
                });
        });

        if (!resList) {
            // 新用户初始化
            this.showFieldList = this.tableColumns;
            const fixKeys = this.fixedFieldList.map((item) => item.id);
            this.selectedFieldList = this.showFieldList.filter((item) => !fixKeys.includes(item.id));
        } else {
            if (resList.length < 1) {
                // 选项为空
                this.showFieldList = this.fixedFieldList;
                this.selectedFieldList = [];
            } else {
                this.showFieldList = this.fixedFieldList.concat(JSON.parse(resList));
                this.selectedFieldList = JSON.parse(resList);
                // const temps = this.fixedFieldList.concat(JSON.parse(resList)).map(item => item.id);
                // this.showFieldList = this.tableColumns.filter(item => temps.includes(item.id));
            }
        }

        this.tableKey++;
    }

    handleButton(type): void {
        if (type == 'search') {
            this.pageChange(1);
        } else if (type == 'doLayout') {
            this.layoutDialog = true;
        } else if (type == 'currentLoadout' || type == 'allLoadout') {
            const exportAll = type == 'allLoadout';
            standardStockExport({
                ...this.searchParam,
                sort: this.sort,
                paging: this.page,
                exportAll,
            });
        }
    }

    getCellStyle({ column }) {
        let value = 'padding: 0; text-align:right';
        let obj = this.tableColumns.find((item) => item.id == column.property);
        if (obj) {
            value = 'padding: 0; text-align: ' + (obj.align || 'right');
        }
        return value;
    }

    getAlign(ele) {
        let obj = this.tableColumns.find((item) => item.id == ele.id);
        return (obj && obj.align) || 'right';
    }
}
</script>
<style lang="scss" scoped>
@import '@/project/pyaxa/pages/report/styles/common';

.isOpened /deep/ .vxe-table {
    .vxe-table--body-wrapper.body--wrapper {
        height: calc(100vh - 305px);
    }
}

.my-input {
    margin: 5px;
    width: 100px;
}
.my-select {
    margin: 5px;
    width: 60px;
}
</style>
